import kivy

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
import os

from landslide import generator

class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

class Root(BoxLayout):
    ti_markdown = ObjectProperty(None)
    ti_theme = ObjectProperty(None)
    
    def select_markdown(self):
        content = LoadDialog(load=self.load_markdown, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9))
        self._popup.open()
        
    def dismiss_popup(self):
        self._popup.dismiss()
        
    def select_theme(self):
        content = LoadDialog(load=self.load_theme, cancel=self.dismiss_popup, dirselect=True)
        self._popup = Popup(title="Select theme", content=content, size_hint=(0.9, 0.9))
        self._popup.open()
            
    def convert(self):
        filePath = self.ti_markdown.text
        fileExt = os.path.splitext(filePath)[1]
        fileDirectory = os.path.dirname(filePath)
        landslide_args = {}
        if fileExt == '.cfg':
            os.chdir(fileDirectory)
        else:
            landslide_args = {"relative":True,
                              "embed":True,
                              "destination_file":"/mnt/sdcard/markdown/presentation.html",
                              "theme": self.ti_theme.text}
        generator.Generator(filePath, **landslide_args).execute()
    
    def load_markdown(self, path, filename):
        path = os.path.join(path, filename[0])
        self.ti_markdown.text = path
        self.dismiss_popup()

    def load_theme(self, path, filename):
        self.ti_theme.text = path
        self.dismiss_popup()
    

class landslideguiApp(App):
    pass

if __name__ == '__main__':
    landslideguiApp().run()